import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { tap, map } from 'rxjs/operators';
import { STComponent, STColumn, STData } from '@delon/abc';
import { Router } from '@angular/router';
@Component({
  selector: 'business-department',
  templateUrl: './department.component.html',
  styles: [`
    .search__form {
      margin-bottom: 0;
    }
  `]
})
export class BusinessDepartmentComponent implements OnInit {
  queryStr: any = {
    offset: 0,
    limit: 10
  };
  data: any[] = [];
  loading = false;
  status = [
    {
      index: 1,
      text: '启用',
      value: false,
      type: 'processing',
      checked: false,
    },
    { index: 2, text: '禁用', value: false, type: 'default', checked: false }
  ];
  @ViewChild('st')
  st: STComponent;
  columns: STColumn[] = [
    { title: '', index: 'key', type: 'checkbox', width: '80px', fixed: 'left'},
    { title: '部门编号', index: 'depCode', width: '120px', fixed: 'left'},
    { title: '部门名称', index: 'depName', width: '120px', fixed: 'left'},
    { title: '上级部门', index: 'depSup', width: '120px'},
    { title: '部门领导', index: 'depLead', width: '120px'},
    { title: '部门人数', index: 'depPersonnel', width: '120px'},
    { title: '部门描述', index: 'depDescribe', width: '120px'},
    {
      title: '状态',
      index: 'depStatus',
      render: 'status',
      filter: {
        menus: this.status,
        fn: (filter: any, record: any) => record.status === filter.index,
      },
      width: '100px'
    },
    {
      title: '创建时间',
      index: 'createAt',
      type: 'date',
      sort: {
        compare: (a: any, b: any) => a.updatedAt - b.updatedAt,
      },
      width: '150px'
    },
    {
      title: '更新时间',
      index: 'updateAt',
      type: 'date',
      sort: {
        compare: (a: any, b: any) => a.updatedAt - b.updatedAt,
      },
      width: '150px'
    },
    {
      title: '操作',
      buttons: [
        {
          text: '编辑',
          click: (item: any) => {
            localStorage['currentData'] = JSON.stringify(item);
            this.router.navigate([`/business/department/add`]);
          },
        },
        {
          text: '删除',
          click: (item: any) => this.remove(item._id),
        },
      ],
      width: '150px',
      fixed: 'right'
    },
  ];
  selectedRows: STData[] = [];
  description = '';
  totalCallNo = 0;
  expandForm = false;
  constructor(
    private http: _HttpClient,
    public msg: NzMessageService,
    private router: Router,
    private modalSrv: NzModalService,
  ) {}
  ngOnInit() {
    this.getData();
  }
  getData() {
    this.loading = true;
    this.queryStr.statusList = this.status
      .filter(w => w.checked)
      .map(item => item.index);
    if (this.queryStr.status !== null && this.queryStr.status > -1)
      this.queryStr.statusList.push(this.queryStr.status);
    this.http
      .get('api/department/list/', this.queryStr)
      .pipe(
        map((res: any) =>
        res.objects.map(i => {
            // const statusItem = this.status[i.depStatus-1];
            i.statusText = i.depStatus;
            i.statusType = i.depStatus==='启用'?'processing':'default';
            return i;
          }),
        ),
        tap(() => (this.loading = false)),
      )
      .subscribe(res => (this.data = res));
  }
  checkboxChange(list: STData[]) {
    this.selectedRows = list;
    this.totalCallNo = this.selectedRows.reduce(
      (total, cv) => total + cv.callNo,
      0,
    );
  }
  reset(ls: any[]) {
    for (const item of ls) item.value = false;
    this.getData();
  }
    // 是否确认删除
    remove(id): void {
    this.modalSrv.confirm({
      nzTitle     : '是否确认删除?',
      nzContent   : '<b style="color: red;">删除后不可恢复</b>',
      nzOkText    : '是',
      nzOkType    : 'danger',
      nzOnOk      : () => {
        this.http.delete('api/department/delete/', {id}).subscribe((res: any) => {
          if(res.success) {
            this.msg.success(`删除成功`);
            this.getData();
            this.st.clearCheck();
          }else{
            this.msg.error(`删除失败`);
          }
        }, () => {
          this.msg.error(`网络或服务器错误`);
        });
      },
      nzCancelText: '否',
      nzOnCancel  : () => console.log('Cancel')
    });
  }
}
